import React, { Component } from "react";
import data from "../mock/data";

interface Istate{
	list: any,
	showData: {id:0,flag:true,title:'',boxOffice:''},
	count: number
}

export default class Home extends Component<{},Istate> {
	constructor(props:any){
		super(props);
		this.state = {
			list: [], //数据列表
			showData: {id:0,flag:true,title:'',boxOffice:''}, //优先展示的数据
			count: 0 //票房总数
		};
	}
		

	componentDidMount() {
		//计算票房总数
		let count = 0;
		data.reduce((prev, current) => {
			count += current.boxOffice;
			return prev;
		}, data);
		this.setState({
			list: this.sort(data),
			count
		});
	}
	//排序
	sort = (arr:any):any => {
		if (arr.length <= 1) {
			return arr;
		}
		let midIndex = Math.floor(arr.length / 2);
		let pivot = arr.splice(midIndex, 1)[0];
		let left = [],
			right = [];
		for (let i = 0; i < arr.length; i++) {
			if (arr[i].boxOffice > pivot.boxOffice) {
				left.push(arr[i]);
			} else {
				right.push(arr[i]);
			}
		}
		return this.sort(left).concat([pivot], this.sort(right));
	};
	//点击★优先展示
	show = (id:number):void => {
		let arr = this.state.list;
		for (let item of arr) {
			if (item.id * 1 === id * 1) {
				item.flag = !item.flag;
				if (item.flag) {
					this.setState({
						showData: item
					});
				} else {
					this.setState({
						showData: {id:0,flag:true,title:'',boxOffice:''}
					});
				}
			} else {
				item.flag = false;
			}
		}
		this.setState({
			list: arr
		});
	};
	render() {
		return (
			<div className="home">
				<div className="left">
					{this.state.showData.flag ? (
						<>
							<div className="top">
								<p>
									<span className="showStar">★</span>
									<span>{this.state.showData.title}</span>
								</p>
								<p>
									综合票房：{this.state.showData.boxOffice}万
								</p>
							</div>
						</>
					) : (
						<>
							<div className="top">
								<span>
									点击<span className="showStar">★</span>
									优先展示
								</span>
							</div>
						</>
					)}
					<div className="bottom">
						<span>总票房：{this.state.count}万</span>
					</div>
				</div>
				<div className="right">
					<ul>
						<li>
							<span>影片</span>
							<span>综合票房（万）</span>
						</li>
						{this.state.list.map((item:any, index:number) => {
							return (
								<li
									key={item.id}
									onClick={() => {
										this.show(item.id);
									}}
								>
									<span>
										{index + 1}
										{item.title}
									</span>
									<span>{item.boxOffice}</span>
									<span
										className={`star ${
											item.flag ? "active" : ""
										}`}
									>
										★
									</span>
								</li>
							);
						})}
					</ul>
				</div>
			</div>
		);
	}
}
